/***
 * Calculator.java
 * @author Isaac Parenteau
 * A basic Android calculator program that does the basic 4 functions
 * plus exp and sqrt
 */
package src.project.calc;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Calculator extends Activity {

	private TextView _display;
	private double first_num = 0;
	private double second_num = 0;
	private boolean clear = false;
	
	private String previousOperator = "";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        _display = (TextView)findViewById(R.id.Display);
        _display.setText("");
        
    }
    
    /***
     * Number click handler. This is triggered
     * when a digit or decimal was selected
     * @param view object that triggered the event
     */
    public void numClick(View view)
    {
    	if(clear)
    		_display.setText("");
    	clear = false;
    	
    	if(previousOperator.equals("="))
    		clearClick(view);
    	
    	Button button = (Button)view;
    	
    	_display.setText((_display.getText().toString() + button.getText().toString()));
    }
    
    /***
     * Operator click handler. This is triggered when
     * anything other than a digit or a decimal was selected
     * @param view object triggering the event
     */
    public void operationClick(View view)
    {
    	clear = true;
    	
    	Button button = (Button)view;
    	
    	    	
    	String operator = button.getText().toString();    	
    	String value = _display.getText().toString();
    	
 
    	if(first_num == 0)
    	{
    		first_num = Double.parseDouble(value);
    	}
    	else
    	{
    		second_num = Double.parseDouble(value);
    	}
    	
    	if(operator.equals("sqrt"))
    	{
    		first_num = Math.sqrt(first_num);
    		operator = "=";
    	}
    	
    	if(!previousOperator.equals("="))
    		calculate();
    	previousOperator = operator;
    	
    	if(operator.equals("="))
    	{
    		_display.setText(String.valueOf(first_num));
    	}

    }
    
    /***
     * Calculates the value based on the operator selected
     */
    public void calculate()
    {
    	if(previousOperator.equals("+"))
    		first_num += second_num;
    	else if(previousOperator.equals("-"))
    		first_num -= second_num;
    	else if(previousOperator.equals("*"))
    		first_num *= second_num;
    	else if(previousOperator.equals("/"))
    		first_num /= second_num;
    	else if(previousOperator.equals("exp"))
    		first_num = Math.pow(first_num, second_num);
    }
    
    /***
     * Clears the content if the clear key "C" was selected
     * @param view
     */
    public void clearClick(View view)
    {
    	first_num = 0;
    	second_num = 0;
    	previousOperator = "";
    	
    	_display.setText("");

    }
}